package main

import (
	"context"
	"flag"
	"fmt"
	"net/http"

	"user/internal/biz"
	"user/internal/config"
	"user/internal/handler"
	"user/internal/queue"
	"user/internal/svc"

	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
)

var configFile = flag.String("f", "etc/user-api.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	//conf.MustLoad(*configFile, &c)
	c = config.PullConfig()

	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()

	server.Use(func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("test-aaaaaaaaaaaa", "true")
			next(w, r)
		}
	})

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	// 统一的错误管理
	httpx.SetErrorHandler(func(err error) (int, any) {
		switch e := err.(type) {
		case *biz.Error:
			fmt.Println(biz.Fail(e))
			return http.StatusOK, biz.Fail(e)
		default:
			return http.StatusInternalServerError, nil
		}
	})

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	//server.Start()
	// 因为使用kafka多服务，所以使用服务组
	serviceGroup := service.NewServiceGroup()
	defer serviceGroup.Stop()

	serviceGroup.Add(server)
	for _, v := range queue.Consumers(c.KqConsumerConf, context.Background(), ctx) {
		serviceGroup.Add(v)
	}
	serviceGroup.Start()

}
